import pygame
from pygame.locals import *
from sys import exit
import scim
import gobject
import string
width=640
height=480
line='#'
showCursor=True
foucus_in=True
class IM_listen(scim.Sample_listener):
    def __init__(self):
        self.loopup_line=''
        self.aux_string=''
    def commit_string(self,str):
        global line
        line+=str
    def update_aux_string(self,str):
        self.aux_string=str
    def hide_aux_string(self):
        self.aux_string=''
    def update_lookup_table(self,list):
        self.loopup_line=' '.join("%d.%s"%(i+1,s) for i,s in enumerate(list) if i<len(list)-1)
    def hide_lookup_table(self):
        self.loopup_line=''
pygame.init()

font=pygame.font.Font('YaHei.Consolas.1.12.ttf',12)
screen = pygame.display.set_mode((width, height), 0,32)
pygame.display.set_caption("Hello, scim!")
manage=scim.Method_input_manager()
instance=manage.new_instance(manage.get_default_factory())
listen=IM_listen()
if not instance:
    print 'instance==NULL'
    exit()
else:
    instance.add_signal_listener(listen)
    instance.focus_in()

    
def on_render():
    global line,showCursor,foucus_in
    for event in pygame.event.get():
        if event.type==QUIT:
            instance.close()
            exit()
        if event.type==KEYDOWN:
            print event
            uc=event.unicode
            c=scim.get_key_name(event.key)
            if c == 'Escape':
                instance.close()
                exit()
            elif c=='space':
                if pygame.key.get_mods() & KMOD_LCTRL or pygame.key.get_mods() & KMOD_RCTRL:
                    if foucus_in:
                        instance.focus_out()
                    else:
                        instance.focus_in()
                    foucus_in=not foucus_in
            if instance.process_key_event(c):
                pass
            elif uc in string.printable:
                line+=uc
            elif event.key==8:
                if line!='#':
                    line=line[:-1]
#    pressed_keys = pygame.key.get_pressed()
#    for key_constant, pressed in enumerate(pressed_keys):
#        if pressed:
#            key_name=pygame.key.name(key_constant)
#            print key_name,key_constant

    screen.fill((255,255,255))
    if showCursor:
       show_line=line+"|"
    else:
        show_line=line         
    screen.blit(font.render(show_line,True,(0,0,0)),(0,0))  
    
    screen.blit(font.render('%s:%s  %s'%(instance.get_name(),listen.aux_string,listen.loopup_line),True,(0,0,0)),(0,height-20))       
    pygame.display.update()
    return True
def update_cursor():
    global showCursor
    showCursor= not showCursor 
    return True      
if __name__=='__main__':
    gobject.timeout_add(int(1000/60),on_render)
    gobject.timeout_add(500,update_cursor)
    gobject.MainLoop().run()